package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.WeiboMapper;
import cn.tedu.egweibo1.pojo.dto.WeiboDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.entity.Weibo;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import cn.tedu.egweibo1.pojo.vo.WeiboDetailVO;
import cn.tedu.egweibo1.pojo.vo.WeiboVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("insert")
    public int insertWeibo(@RequestBody WeiboDTO weiboDTO, HttpSession session){
        /**
         * 插入内容
         * 1.确认是否登录状态
         * 2.调用key数据
         * 3.插入微博内容
         */

        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null){
            return 2;
        }   //session key确认登入状态

        Weibo weibo = new Weibo();  //插入weibo表
        BeanUtils.copyProperties(weiboDTO,weibo); //插入content
        weibo.setUserId(userVO.getId());    //useId=key内数据id
        weibo.setCreated(new Date());

        weiboMapper.insertWeibo(weibo);

        return 1;
    }

    @GetMapping("selectIndex")
    public List<WeiboVO> selectIndex(){
        return weiboMapper.selectIndex();
    }

    @GetMapping("selectById")
    public WeiboDetailVO selectByID(Integer id){

        return weiboMapper.selectByID(id);
    }
}
